<template>
	<view style="margin-left: 13px; margin-right: 13px;margin-top: 8px;margin-bottom: 8px;">
		设备：{{loginWorkInfo.workCenterName}}</view>
	<u-line></u-line>
	<!-- 第一行 -->
	<view style="margin-left: 13px; margin-right: 13px;margin-top: 8px;margin-bottom: 8px;">
		<!-- 工作执中心名称+？ -->
		<label>{{loginWorkInfo.workCenterCode+'-'}}</label>
		<label>{{loginWorkInfo.workCenterName}}</label>
		<label style=" float: right;">{{crewMemberList[0]?.memberName || '暂无'}}</label>
	</view>
	<u-line></u-line>
	<!-- 第二行 -->
	<view style="margin-left: 13px; margin-right: 13px;margin-top: 8px;margin-bottom: 8px;">
		<!-- 物料编号+数量 -->
		<label>{{workOrderList[0]?.materialCode || '暂无'}}</label>
		<label style=" float: right;">批次数量：{{workOrderList[0]?.planBatchNum || '暂无'}}</label>
	</view>
	<u-line></u-line>
	<!-- 第二行 新增的，当当前为关闭状态时展示-->
	<view v-show="currentWorkOrder?.isClosed === 1" style="margin-left: 13px; margin-right: 13px;margin-top: 8px;margin-bottom: 8px;">
		<!-- 物料编号+数量 -->
		<label>派工单已关闭</label>
		<label style=" float: right;">完成数量：{{ workOrderList[0]?.planFinishQuantity || 0 }}</label>
	</view>
	<u-line v-show="currentWorkOrder?.isClosed === 1"></u-line>
	<!-- 第三行 -->
	<view style="margin-left: 13px; margin-right: 13px;margin-top: 8px;margin-bottom: 8px;">
		<!-- 生产批次+班组登录人数 -->
		<label>{{workOrderList[0]?.planBatch || '暂无'}}</label>
<!-- 		<label
			style=" float: right;">{{loginWorkInfo.crewName}}：{{crewMemberList.length}}/{{crewMemberAll.length}}人</label> -->
	</view>
	<u-line></u-line>
	<view class="baseForm">
		<u--form labelPosition="left" :model="umodel" :rules="rules" ref="uForm" labelWidth="160rpx" errorType="toast">
			<u-form-item label="成员登录" label-width="100px" prop="memberEmpNo" style=" font-weight: 700;">
				<!-- 条码录入 -->
				<!-- <scan-bar ref="scanBarRef" @code-scanned="crewMemberLogin" class="scan-bar"></scan-bar> -->
				<u-input placeholder="请输入工号" v-model="umodel.memberEmpNo" border="none" style="font-weight: 500;"></u-input>
				<u-button style=" width: 50px; margin-left: 10px;" @click="crewMemberLogin(umodel.memberEmpNo)"
					size="small" type="primary">登录</u-button>
			</u-form-item>
		</u--form>
		<u-line></u-line>
		<!-- 卡片显示 -->
		<view class="list">
			<!-- <text class="list-title">班组成员({{ crewMemberList.length }})</text> -->
			<view class="card" v-for="item in crewMemberList" :key="item.id">
				<view class="right">
					<view class="title">
						姓名：{{ item.memberName}}
					</view>
				</view>
				<view class="delete">
					<u-icon name=">" color="#999" size="16px" @click="deleteItem(item)"></u-icon>
					<u-modal :show="show" @confirm="confirm" @cancel="cancel" :content='content'
						:showCancelButton="true">
					</u-modal>
				</view>
			</view>
			<u-line></u-line>
			<view  class="card" @click="openTimeSelect()">
				<view class="right" >
					<view class="title">
						下班时间：
					</view>
				</view>
				<view class="left"  @click="openTimeSelect()">
				<u--input v-model="umodelTime.startTime" border="none" inputAlign="right" disabled disabledColor="#ffffff" placeholder="请选择时间"></u--input>
				<u-datetime-picker :show="showTime" v-model="umodelTime.startTimeA"  mode="datetime" @cancel="showTime = false" @confirm="timeSelect"></u-datetime-picker>
				</view>

			</view>
			<u-button style=" width: 150px; margin-top: 10px;" @click="showLoginOut = true"
				size="small" type="primary">成员下班退出登录</u-button>
		</view>
		<!-- 重复添加显示 -->
		<u-toast ref="uToastRef"></u-toast>
		<u-modal
			width="500rpx"
			:show="showLoginOut"
			content="是否班组全部下班退出(包括自己)？"
			showCancelButton
			@confirm="allLogout"
			@cancel="showLoginOut = false"
			ref="uModal"
			style="text-align: center"
		></u-modal>
	</view>
</template>

<script lang="ts" setup>
	import { ref, reactive, computed, toRaw } from 'vue';
	import { onPageScroll, onPullDownRefresh } from '@dcloudio/uni-app';
	import { http } from '@/utils/http';
	import { useUserStore } from '@/stores/useUserStore';
	import { getTimes } from '@/utils/common';
	import { useProduceStore } from '@/stores/useProduceStore';
	// loginWorkInfo
	const loginWorkInfo = computed(() => JSON.parse(useUserStore().loginWorkInfo));

	console.log('loginWorkInfo', loginWorkInfo.value)
	//token获取
	// console.log(useUserStore().token)

	// 加工单信息
	const workOrderList = computed(() => JSON.parse(useProduceStore().workOrderList));
	console.log('加工单', workOrderList.value)
	const umodelTime = reactive({
		startTime:getTimes(Date.now()),
		startTimeA:getTimes(Date.now()),
	});
	const showTime = ref(false);
	// 班组信息获取
	let crewMemberList = computed(() => JSON.parse(useProduceStore().crewMemberList));
	console.log('班组已登录员工', crewMemberList.value)
	//推出时传递所选值信息
	function deleteItem(item) {
		crewMember.value = item
		show.value = true
	}

	//获取当前班组所以人员
	// getCrewMemberAll()
	const crewMemberAll : any = ref([])
	async function getCrewMemberAll() {
		await http({
			method: 'POST',
			url: '/mes/mescrew/getCrewMembers',
			data: {
				id: loginWorkInfo.value.crewId
			},
		}).then((res) => {
			crewMemberAll.value = res.data
		})
	}
	//点击推出时提醒内容
	const content = ref('确定要退出此用户吗？');


	// 监听页面到顶部距离
	const scrollTop = ref(0)
	onPageScroll((e) => {
		scrollTop.value = e.scrollTop
	})
	// 时间选择
	function timeSelect(e) {
		console.log(e);
		umodelTime.startTimeA = e.value
		umodelTime.startTime = getTimes(e.value);
		console.log(umodelTime.startTime);
		showTime.value = false;
	}

	function openTimeSelect() {
		showTime.value = true;
		uni.hideKeyboard();
	}
	// 表单数据定义
	const umodel = reactive({
		dropdownShow: true,
		searchSuggestions: ['apple', 'banana', 'cherry', 'date', 'elderberry'],
		id: '',
		organizationId: '',
		organizationCode: '',
		organizationName: '',
		plantId: '',
		plantCode: '',
		plantName: '',
		workCenterId: '',
		workCenterCode: '',
		workCenterName: '',
		crewId: '',
		crewCode: '',
		memberRoleId: '',
		memberRoleName: '',
		memberId: '',
		memberName: '',
		loginType: '',
		loginTime: '',
		version: '',
		remarks: '',
		memberEmpNo: '',
	});

	// 表单规则定义
	const rules = ref({
		memberEmpNo: [{
			message: '请输入工号',
			trigger: ['blur', 'change'],
		}]
	});
	//推出弹出开关
	const show = ref(false);


	// 重置表单
	const uForm = ref();

	const crewMember = ref({})
	//班组员工登录请求
	async function crewMemberLogin(code : string) {
		umodel.memberEmpNo = ""
		if (!code) {
			return
		}
		// 从数组中找到对应的项的索引
		const index = crewMemberList.value.findIndex(i => i.memberEmpNo === code);
		// 如果找到了对应的索引
		if (index !== -1) {
			// 使用 splice 方法删除对应的项
			// console.log("已经登录无需重复扫描")
			showToast(list.value[0])
			return
		}

		await http({
			method: 'POST',
			url: '/mes/mesmemberloginrecord/login',
			data: {
				workCenterId: loginWorkInfo.value.workCenterId,
				crewId: loginWorkInfo.value.crewId,
				memberEmpNo: code,
			},
		}).then((res) => {
			if (res.code == "200") {
				useProduceStore().setCrewMemberList([...crewMemberList.value, res.data]);
				crewMemberList = computed(() => JSON.parse(useProduceStore().crewMemberList));
				console.log("crewMemberList",crewMemberList)
			}
		})

		// console.log(result)
	}
	const showLoginOut = ref(false);

	//班组下班退出触发函数
	const allLogout = async () => {
		if(!umodelTime.startTime) {
			uni.$u.toast('集体下班请填写下班时间！');
		}
		console.log(crewMember.value)
		showLoginOut.value = false;
		await http({
			method: 'POST',
			url: '/mes/mesmemberloginrecord/logOutBatch',
			data: {
				memberLoginRecordDTOS: crewMemberList.value,
				loginTime: umodelTime.startTime,
			},
		}).then((res) => {
			if (res.code == "200") {
				useProduceStore().setCrewMemberList(null);
				useUserStore().logout();
			}
		})
		show.value = false;
	
	};
	//退出确定触发函数
	const confirm = async () => {
		console.log(crewMember.value)
		// 从数组中找到对应的项的索引
		const index = crewMemberList.value.findIndex(i => i.memberEmpNo === crewMember.value.memberEmpNo);
		// console.log(index)
		if (index == 0) {
			uni.$u.toast('该用户无法退出登录！');
			show.value = false;
			return
		}
		// 如果找到了对应的索引
		if (index !== -1) {
			console.log("删除" + index)
			let list = JSON.parse(JSON.stringify(crewMemberList.value));
			list.splice(index, 1);
			useProduceStore().setCrewMemberList(list);
			
		}
		if(!umodelTime.startTime) {
			uni.$u.toast('退出下班，请填写退出时间！');
		}
		await http({
			method: 'POST',
			url: '/mes/mesmemberloginrecord/logOut',
			data: {
				workCenterId: loginWorkInfo.value.workCenterId,
				crewId: loginWorkInfo.value.crewId,
				loginTime: umodelTime.startTime,
				memberEmpNo: crewMember.value.memberEmpNo,
			},
		}).then((res) => {
			if (res.code == "200") {
				crewMemberList = computed(() => JSON.parse(useProduceStore().crewMemberList));
				console.log("crewMemberList",crewMemberList)
			}
		})
		show.value = false;

	};
	//取消关闭弹出框触发函数
	const cancel = () => {
		show.value = false;
	};

	// 创建响应式数据  
	const list = ref([
		{
			type: 'default',
			title: '默认主题',
			message: "已经登录无需重复扫描",
			iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/default.png'
		},
	]);

	// 方法
	const uToastRef = ref(null)
	function showToast(params) {
		uToastRef.value.show({
			...params,
			complete() {
				params.url && uni.navigateTo({
					url: params.url
				});
			}
		});
	}
	
	const currentWorkOrder = ref();
	async function getCurrentWorkOrder() {
	  const id = workOrderList.value[0]?.id;
	  if (id) {
	    const { data } = await http({
	      method: "GET",
	      url: "/mes/mesplannedbatch/get/" + id,
	      data: {},
	    }).finally(() => {});
	    currentWorkOrder.value = data;
	    if (data?.orderState == 5) {
			uni.$u.toast('当前加工单已关闭，请前往加工单页面重新选择');
	    }
	  }
	}
	
	onShow(()=>{
		getCurrentWorkOrder()
	})
</script>

<style lang="scss" scoped>
	.baseForm {
		padding: $uni-page-padding;
		padding-bottom: 30px;
		margin: 15px 0 0 0;

		.u-form {
			margin-top: 5px;

			:deep(.u-form-item__body) {
				padding: 5px 0;
			}

			.u-input {
				border: 1px solid $uni-input-border-color;
			}

			.scan-bar {
				display: flex;
				flex: 1;
			}
		}

		.u-line {
			padding: 10px 0;
		}

		.search {
			display: flex;

			.custom-style {
				// width: 120px;
				margin: 10px 5px 5px;
				height: 36px;
				border-radius: 8px;

				&:nth-child(1) {
					flex: 1
				}

				&:nth-child(2) {
					flex: 3
				}
			}
		}

		.list {
			.list-title {
				line-height: 40px;
				font-size: 14px;
				color: rgba(0, 0, 0, 0.4);
			}

			.card {
				margin-top: 5px;
				margin-bottom: 10px;
				border-radius: 7px;
				display: flex;
				align-items: center;
				padding: 10px 0;
				transition: all 300ms ease;
				box-shadow: 0 0 1px rgba(0, 0, 0, 0.1);

				.left {
					// flex-basis: 90rpx;
					padding-right: 10px;
					text-align: right;
					font-size: 13px;

					.enter {
						line-height: 20px;
						margin-bottom: 5px;
					}

					.number {
						font-size: 13px;
						line-height: 18px;
					}

					:deep(.u-icon--right) {
						flex-direction: row-reverse;
					}
				}

				.right {
					flex: 1;
					padding-left: 15px;

					.title {
						font-size: 15px;
						line-height: 20px;
						margin-bottom: 5px;
					}

					.body {
						color: rgba(0, 0, 0, 0.4);
						font-size: 13px;
						line-height: 18px;
					}
				}
			}
		}
	}
</style>